const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin =require("mini-css-extract-plugin");
const project = fs.readFileSync('.development', 'utf-8');
const mode = process.argv[process.argv.length - 1] || 'develpment'

console.log('当前项目：', project)
function getProjectConfig(){
  let config = {}
  try{
    config = yaml.load(fs.readFileSync(`./src/project/${project}/config.yml`, 'utf8'));
    console.log(`配置信息：${JSON.stringify(config)}`)
  } catch (e) {
    console.log('配置信息：没有配置文件config.yml')
  } finally {
    if (!config.projectType) {
      const content = fs.readFileSync(`./src/project/${project}/app.js`, 'utf8')
      if (content.indexOf('vue') > -1) {
        config.projectType = 'vue'
      } else if (content.indexOf('react') > -1) {
        config.type = 'react'
      }
    }
  }
  return config
}
const { title = 'xxxxxx', projectType } = getProjectConfig()
const config = {
  mode,
  devtool: mode === 'development' ? 'source-map' : 'cheap-module-source-map',
  entry: {
    app: path.join(__dirname, 'src', 'project', project, 'app.js'),
  },
  output: {
    filename: 'js/[name].js?t=[contenthash]',
    path: path.resolve(__dirname, `dist/${project}`),
    chunkFilename: 'js/[name].chunk.js?t=[contenthash]',
    assetModuleFilename: 'images/[name][ext]?t=[contenthash]',
    clean: true,
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@project': path.resolve(__dirname, './src/project'),
    }
  },
  performance: false, //关闭性能分析，提高打包速度。
  cache: {
    //可开启webpack5内置缓存
    type: 'filesystem',
    allowCollectingMemory: true,
  },
  plugins: [
    new HtmlWebpackPlugin({ title, template: './public/index.html' }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css?t=[contenthash]',
      chunkFilename: 'css/[name].chunk.css?t=[contenthash]',
    }),
  ],
  devServer: {
    hot: true,
    open: true,
    historyApiFallback: true
  },
  optimization: {
    runtimeChunk: 'single',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.less$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', {
          loader: 'less-loader',
          options: {
            lessOptions: {
              modifyVars: {
                'link-color': '#1DA57A',
                'primary-color': '#1DA57A',
                'border-radius-base': '2px',
              }
            },
            javascriptEnabled: true,
          }
        }],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: 'all', //代码分割
      cacheGroups: {
        react: {
          //react react-dom react-router-dom 一起打包成一个js文件
          test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,
          name: 'chunk-react',
          priority: 40, //打包优先级权重
        },
        vue: {
          //react react-dom react-router-dom 一起打包成一个js文件
          test: /[\\/]node_modules[\\/]vue(.*)?[\\/]/,
          name: 'chunk-vue',
          priority: 40, //打包优先级权重
        },
        antd:{ //antd单独打包
            test:/[\\/]node_modules[\\/]antd[\\/]/,
            name:'chunk-antd',
            priority:30,
        },
        lib: {
          //node_modules单独打包
          test: /[\\/]node_modules[\\/]/,
          name: 'chunk-lib',
          priority: 20,
        },
      },
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime-${entrypoint.name}.js`, //单独储存引用的chunk的打包地址，main.js不会随着其他模块的变化导致地址变化而打包变化
    },
  },
}
function createWebPackConfig(){
  const [reactRule, ...vueRule] = [
    {
      test: /\.jsx?$/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react'],
        },
      },
    },
    {
      test: /\.vue$/i,
      use: ['vue-loader'],
    }, 
    {
      test: /\.js?$/i,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
          plugins: ['@vue/babel-plugin-jsx'],
        },
      },
    }
  ]
  if (projectType === 'react'){
    config.module.rules.push(reactRule)
  }
  if (projectType === 'vue') {
    config.module.rules.push(...vueRule)
    config.plugins.push(new VueLoaderPlugin())
  }
  return config
}

module.exports = createWebPackConfig()